﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerArchitecture.Core;
using ComputerArchitecture.Core.Logging;
using ComputerArchitecture.Numbers;
using ComputerArchitecture.Units.Interfaces;

namespace ComputerArchitecture.Units.Complement
{
    public class ComplementNegateUnit : LoggingObject, INegateUnit
    {
        #region Fields

        private readonly IAdderUnit _adderUnit;

        #endregion

        #region Constructors

        public ComplementNegateUnit(ILoggingService loggingService, IAdderUnit adderUnit)
            : base(loggingService)
        {
            ArgumentValidator.NullValidate(adderUnit);
            _adderUnit = adderUnit;
        }

        #endregion

        #region Methods

        public ISignedBitNumber Negate(ISignedBitNumber value, out NegateSpecialCase specialCase, out bool hasError)
        {
            ArgumentValidator.NullValidate(value);
            ISignedBitNumber zero = ComplementBitNumber.GetZero(value.Size);
            if (value.Equals(zero))
            {
                hasError = true;
                specialCase = NegateSpecialCase.Zero;
                this.LoggingService.LogWarning("Warning! Try to negate zero ({0:d4})", value);
                return zero;
            }
            ISignedBitNumber min = ComplementBitNumber.GetMin(value.Size);
            if (value.Equals(min))
            {
                hasError = true;
                specialCase = NegateSpecialCase.MaxNegativeValue;
                this.LoggingService.LogWarning("Warning! Try to negate min value ({0:d4})", value);
                return min;
            }
            hasError = false;
            specialCase = NegateSpecialCase.None;
            ISignedBitNumber negate = (ISignedBitNumber) value.Clone();
            negate.Negate();
            ISignedBitNumber one = ComplementBitNumber.GetOne(value.Size);
            bool overflow;
            return _adderUnit.Add(negate, one, out overflow);
        }

        #endregion
    }
}
